﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;

public class GrapplingGunL : MonoBehaviour
{
    private LineRenderer lr;
    private Vector3 grapplePoint;
    public LayerMask grappleable;
    public Transform muzzl, camera, player;
    private float maxDistance = 100f;
    private SpringJoint joint;   //弹簧;

    private void Awake()
    {
        lr = GetComponent<LineRenderer>();
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartGeapple();
        }
        else if (Input.GetMouseButtonUp(0))
        {
            StopGrapple();
        }
    }

    private void LateUpdate()
    {
        DrawRope();
    }

    void StartGeapple()
    {
        RaycastHit hit;
        if(Physics.Raycast(origin: camera.position, direction: camera.forward, out hit, maxDistance, grappleable))
        {
            grapplePoint = hit.point;
            joint = player.gameObject.AddComponent<SpringJoint>();
            joint.autoConfigureConnectedAnchor = false;
            joint.connectedAnchor = grapplePoint;

            float distanceFromPoint = Vector3.Distance(a: player.position, b: grapplePoint);

            joint.maxDistance = distanceFromPoint * 0.5f;
            joint.minDistance = distanceFromPoint * 0.25f;

            joint.spring = 80f;
            joint.damper = 10f;
            joint.massScale = 4.5f;

            lr.positionCount = 2;

        }
    }

    void StopGrapple()
    {
        lr.positionCount = 0;
        Destroy(joint);
    }

    void DrawRope()
    {
        if (!joint) return;

        lr.SetPosition(index: 0, muzzl.position);
        lr.SetPosition(index: 1, grapplePoint);
    }

}
